import React, { useState, useEffect } from 'react'
import moment from 'moment'
function TimeComponent(props) {
    const { createTime } = props;
    const [timeState, setTimeState] = useState(moment().valueOf() - moment(createTime).valueOf())


    useEffect(() => {
        const timeUpdate = setInterval(() => {
            let seconds = moment().valueOf() - moment(createTime).valueOf()
            setTimeState(seconds);
        }, 1000);
        return () => {
            clearInterval(timeUpdate);
        };
    }, []);
    return formatSeconds(timeState / 1000)

}

export default TimeComponent;


//秒数转化为天时分秒 
export const formatSeconds = (value, symbol) => {
    var secondTime = parseInt(value);// 秒
    var minuteTime = 0;// 分
    var hourTime = 0;// 小时
    var dayTime = 0;// 天
    if (secondTime > 60) {//如果秒数大于60，将秒数转换成整数
        //获取分钟，除以60取整数，得到整数分钟
        minuteTime = parseInt(secondTime / 60);
        //获取秒数，秒数取余，得到整数秒数
        secondTime = parseInt(secondTime % 60);
        //如果分钟大于60，将分钟转换成小时
        if (minuteTime > 60) {
            //获取小时，获取分钟除以60，得到整数小时
            hourTime = parseInt(minuteTime / 60);
            //获取小时后取余的分，获取分钟除以60取余的分
            minuteTime = parseInt(minuteTime % 60);

            if (hourTime > 24) {
                dayTime = parseInt(hourTime / 24);
                //获取小时后取余的分，获取分钟除以60取余的分
                hourTime = parseInt(hourTime % 24);
            }
        }
    }
    var result = symbol ? '' : "" + (parseInt(secondTime) < 10 ? '0' + parseInt(secondTime) : parseInt(secondTime));
    result = "" + ((!symbol && parseInt(minuteTime) < 10) ? '0' + parseInt(minuteTime) : parseInt(minuteTime)) + (symbol ? '分钟' : ":") + result;
    result = (symbol && parseInt(hourTime) == 0) ? result : "" + (!symbol && parseInt(hourTime) < 10 ? '0' + parseInt(hourTime) : parseInt(hourTime)) + (symbol ? '小时' : ":") + result;
    if (dayTime > 0) {
        result = "" + parseInt(dayTime) + "天 " + result;
    }
    // console.log('result', result);

    return result;
}